package com.itheima.job;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 自定义Job，实现定时清理垃圾图片
 */
@Component
public class ClearImgJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Scheduled(cron = "0 0 0 * * ?") // 每天的午夜12点执行一次
//    @Scheduled(cron = "0/10 * * * * ?") // 测试的10秒执行一次
    public void clearImg() {
        System.out.println("定时任务。。。。");
        //根据Redis中保存的两个set集合进行差值计算，获得垃圾图片名称集合
        Set<String> set =  redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES,
                        RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if (set != null) {
            for (String picName : set) {
                // 删除阿里云图片
                aliOssUtil.delete(picName);
            }
            //从Redis集合中删除图片名称
            redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,set);
        }
    }
}